package com.gw.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


@Component
public class RedisUtil { //操作Redis缓存的
    @Autowired //自动注入RedisTemplate
    private StringRedisTemplate redisTemplate;

    /**
     * 读取缓存
     * @param key
     * @return String
     */
    public String get(final String key){
        return redisTemplate.opsForValue().get(key);

    }


    /**
     * 写入缓存
     * @param key
     * @param value
     * @return boolean
     */
    public boolean set(final String key,String value){
        boolean result=false;
        try {
            redisTemplate.opsForValue().set(key,value);
            result=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     * @param key
     * @param value
     * @return
     */
    public boolean getAndSet(final String key,String value){
        boolean result=false;
        try {
            redisTemplate.opsForValue().getAndSet(key,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return  result;
    }

    /**
     * 删除缓存
     * @param key
     * @return
     */
    public boolean delete(final String key){
        boolean result=false;
        try {
            redisTemplate.delete(key);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
